<?php

namespace app\api\model\user;

use app\api\model\Setting as SettingModel;
use app\api\model\user\PointsLog as PointsLogModel;
use app\common\model\user\Signin as SigninModel;
use think\Db;

/**
 * 签到
 */
class Signin extends SigninModel
{
    protected $autoWriteTimestamp = false;
    /**
     * 签到天数
     */
    public static function day($num)
    {
        switch ($num) {
            case 0:
                $day = 'seven';
                break;
            case 1:
                $day = 'one';
                break;
            case 2:
                $day = 'two';
                break;
            case 3:
                $day = 'three';
                break;
            case 4:
                $day = 'four';
                break;
            case 5:
                $day = 'five';
                break;
            case 6:
                $day = 'six';
                break;
            default:
                $day = '';
                break;
        }
        return $day;
    }

    /**
     * 签到积分
     */
    public static function signin($user)
    {
        $yesterday = self::getUserLog($user->user_id, 'yesterday');
        if (!$yesterday) {
            $day = 'one';
        } else {
            $day = self::day($user->signin_num % 7);
        }
        //积分
        $points = SettingModel::getPointsName('signin')[$day];
        Db::startTrans();
        try {
            //签到记录
            self::addSignin($user->user_id);
            //积分明细
            PointsLogModel::addSignin($user->user_id, $points);
            //连续签到天数
            $user->points += $points['points'];
            $user->signin_num = $yesterday ? $user->signin_num + 1 : 1;
            $user->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        return isset($e) ? false : true;
    }

    /**
     * 获取昨天、今天等时间记录
     */
    public static function getUserLog($user_id, $time)
    {
        return self::where('user_id', $user_id)->whereTime('create_time', $time)->find();
    }

    /**
     * 积分记录
     */
    public static function addSignin($user_id)
    {
        return static::add([
            'user_id' => $user_id,
            'time' => date('Y-m-d', time()),
            'create_time' => time()
        ]);
    }

    /**
     * 本月签到记录
     */
    public static function month($user_id)
    {
        return self::where('user_id', $user_id)->whereTime('create_time', 'month')->select();
    }


}